package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.IHotelService;
import cn.itcast.hotel.vo.PageResult;
import cn.itcast.hotel.vo.RequestParams;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public PageResult search(RequestParams params) {
        SearchRequest searchRequest = new SearchRequest("hotel");
        buildBasicSearch(searchRequest, params);
        // 分页
        Integer pageNumber = params.getPage() == null ? 1 : params.getPage();
        Integer pageSize = params.getSize() == null ? 1 : params.getSize();
        searchRequest.source().from((pageNumber - 1) * pageSize).size(pageSize);
        // 排序
        if (StringUtils.isNotBlank(params.getLocation())) {
            searchRequest.source().sort(
                    SortBuilders.geoDistanceSort("location", new GeoPoint(params.getLocation()))
                            .order(SortOrder.ASC)
                            .unit(DistanceUnit.KILOMETERS)
            );
        }


        SearchResponse response = null;
        try {
            response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException("查询异常" + e);
        }
        // 解析
        return handlerResult(response);
    }

    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        Map<String, List<String>> info = new HashMap<>();
        SearchRequest request = new SearchRequest("hotel");
        request.source().size(0);
        buildBasicSearch(request, params);
        // 构建聚合
        buildAggs(request);
        // 发起请求
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            List<String> cities = getBuckNames(response, "cityAgg");
            List<String> brands = getBuckNames(response, "brandAgg");
            List<String> starNames = getBuckNames(response, "starNameAgg");
            info.put("city", cities);
            info.put("brand", brands);
            info.put("starName", starNames);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return info;
    }

    @Override
    public List<String> getSuggestions(String prefix) {
        ArrayList<String> texts = new ArrayList<>();
        SearchRequest request = new SearchRequest("hotel");
        request.source().suggest(new SuggestBuilder().addSuggestion(
                "hotelSuggestion",
                SuggestBuilders
                        .completionSuggestion("suggestion")
                        .prefix(prefix)
                        .skipDuplicates(true)
                        .size(10)
        ));
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            Suggest suggest = response.getSuggest();
            CompletionSuggestion hotelSuggestion = suggest.getSuggestion("hotelSuggestion");
            if (hotelSuggestion != null && CollectionUtils.isNotEmpty(hotelSuggestion.getOptions())) {
                List<CompletionSuggestion.Entry.Option> options = hotelSuggestion.getOptions();
                for (CompletionSuggestion.Entry.Option option : options) {
                    String text = option.getText().string();
                    texts.add(text);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return texts;
    }

    private List<String> getBuckNames(SearchResponse response, String aggName) {
        List<String> aggs = new ArrayList<>();
        Aggregations aggregations = response.getAggregations();
        Terms terms = aggregations.get(aggName);
        if (terms == null && CollectionUtils.isEmpty(terms.getBuckets())) {
            return aggs;
        }
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            aggs.add(bucket.getKeyAsString());
        }
        return aggs;
    }

    private void buildAggs(SearchRequest request) {
        request.source().aggregation(AggregationBuilders.terms("cityAgg").field("city").size(20));
        request.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(20));
        request.source().aggregation(AggregationBuilders.terms("starNameAgg").field("starName").size(20));
    }

    private void buildBasicSearch(SearchRequest searchRequest, RequestParams params) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 模糊查询
        if (StringUtils.isNotBlank(params.getKey())) {
            boolQuery.must(QueryBuilders.matchQuery("all", params.getKey()));
        } else {
            boolQuery.must((QueryBuilders.matchAllQuery()));
        }
        // 过滤
        if (StringUtils.isNotBlank(params.getBrand())) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        if (StringUtils.isNotBlank(params.getCity())) {
            boolQuery.filter(QueryBuilders.termQuery("city", params.getCity()));
        }
        if (StringUtils.isNotBlank(params.getStarName())) {
            boolQuery.filter(QueryBuilders.termQuery("starName", params.getStarName()));
        }
        if (params.getMaxPrice() != null && params.getMinPrice() != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(params.getMinPrice()).lte(params.getMaxPrice()));
        }
        // 算分查询
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", "true"),
                                ScoreFunctionBuilders.weightFactorFunction(20f))
                }
        );
        functionScoreQueryBuilder.boostMode(CombineFunction.MULTIPLY); //设置加权
        searchRequest.source().query(functionScoreQueryBuilder);
    }

    private PageResult handlerResult(SearchResponse response) {
        if (Objects.isNull(response)) {
            return null;
        }
        SearchHits searchHits = response.getHits();
        long total = searchHits.getTotalHits().value;
        SearchHit[] hits = searchHits.getHits();
        ArrayList<HotelDoc> hotelDocs = new ArrayList<>();
        if (ArrayUtils.isNotEmpty(hits)) {
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                HotelDoc hotelDoc = JSON.parseObject(sourceAsString, HotelDoc.class);
                // 距离
                Object[] sortValues = hit.getSortValues();
                if (ArrayUtils.isNotEmpty(sortValues)) {
                    hotelDoc.setDistance(sortValues[0]);
                }
                hotelDocs.add(hotelDoc);
            }
        }
        // 组装
        return new PageResult(total, hotelDocs);
    }
}
